import 'package:langaw/components/fly.dart';
import 'package:langaw/langaw-game.dart';

class FlySpawner {
  final LangawGame game;

  ///This constant is the upper limit on when to spawn flies.
  ///When the game starts, the currentInterval is set to the value of maxSpawnInterval.
  ///Which is 3000 milliseconds or three seconds.
  final int maxSpawnInterval = 3000;

  ///minSpawnInterval, is the exact opposite of this.
  /// Every time a fly is spawned the currentInterval variable is reduced but only down to this point which is 250 milliseconds.
  /// Or 1/4 of a second.
  final int minSpawnInterval = 250;

  ///intervalChange, is the amount that is reduced from currentInterval every time a fly is spawned.
  ///So starting from 3 seconds flies spawn faster and faster every time one is spawned until it gets down to 1/4 of a second but no less.
  ///This is the fastest and I’m imagining if a player gets this far it will be chaos even though there’s a limit to how many flies can be on the screen at any moment.
  final int intervalChange = 3;

  ///Even if the game gets to point where it’s crazy fast in spawning flies, it will not spawn more as long as there are seven flies alive and flying around.
  final int maxFliesOnScreen = 7;

  ///The variable currentInterval stores the amount of time to be added from the current time when scheduling the next spawn.
  int currentInterval;

  /// nextSpawn is the actual time that is scheduled for the next spawn.
  /// This variable holds a value that measures the time in milliseconds since the beginning of the Unix epoch (January 1, 1970, 12 midnight GMT).
  int nextSpawn;

  FlySpawner(this.game) {
    start();
    game.spawnFly();
  }

  void start() {
    killAll();
    currentInterval = maxSpawnInterval;
    nextSpawn = DateTime.now().millisecondsSinceEpoch + currentInterval;
  }

  void killAll() {
    game.flies.forEach((Fly fly) => fly.isDead = true);
  }

  void update(double t) {
    int nowTimestamp = DateTime.now().millisecondsSinceEpoch;

    int livingFlies = 0;
    game.flies.forEach((Fly fly) {
      if (!fly.isDead) livingFlies += 1;
    });

    if (nowTimestamp >= nextSpawn && livingFlies < maxFliesOnScreen) {
      game.spawnFly();
      if (currentInterval > minSpawnInterval) {
        currentInterval -= intervalChange;
        currentInterval -= (currentInterval * .02).toInt();
      }
      nextSpawn = nowTimestamp + currentInterval;
    }
  }
}
